﻿using System;
using System.Collections.Generic;
using System.Collections;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Core;
using Core.IO;

public partial class Lesktop_Management_UpdateAccountInfo : System.Web.UI.Page
{
	protected void Page_Load(object sender, EventArgs e)
	{
		AccountInfo cu = Core.ServerImpl.Instance.GetCurrentUser(Context);
		AccountInfo groupInfo = Core.AccountImpl.Instance.GetUserInfo(Request.QueryString["Name"]);
		if (String.Compare(cu.Name, groupInfo.Creator, true) != 0)
		{
			throw new Exception("权限不足！");
		}

		CommandCtrl cmdCtrl = FindControl("CommandCtrl1") as CommandCtrl;
		cmdCtrl.OnCommand += new CommandCtrl.OnCommandDelegate(cmdCtrl_OnCommand);
		cmdCtrl.State["AccountInfo"] = groupInfo.DetailsJson;
	}

	private void cmdCtrl_OnCommand(string command, object data)
	{
		CommandCtrl cmdCtrl = FindControl("CommandCtrl1") as CommandCtrl;
		AccountInfo groupInfo = Core.AccountImpl.Instance.GetUserInfo(Request.QueryString["Name"]);
		try
		{
			if (command == "Update")
			{
				Hashtable info = data as Hashtable;
				if (Request.Files["file_headimg"] != null && Request.Files["file_headimg"].InputStream.Length > 0)
				{
					String filename = String.Format("/{0}/pub/{1}{2}", groupInfo.Name, Guid.NewGuid().ToString().Replace("-", ""), Path.GetExtension(Request.Files["file_headimg"].FileName));
					info["HeadIMG"] = filename;
					Directory.CreateDirectory(Path.GetDirectoryName(filename));
					using (System.IO.Stream stream = File.Open(filename, System.IO.FileMode.Create, System.IO.FileAccess.Write, System.IO.FileShare.None))
					{
						byte[] buffer = new byte[4 * 1024];
						while (true)
						{
							int c = Request.Files["file_headimg"].InputStream.Read(buffer, 0, buffer.Length);
							if (c == 0) break;
							stream.Write(buffer, 0, c);
						}
					}
				}

				AccountImpl.Instance.UpdateUserInfo(groupInfo.Name, info);

				foreach (string friend in groupInfo.Friends)
				{
					AccountInfo friendInfo = AccountImpl.Instance.GetUserInfo(friend);
					if (friendInfo.Type == 0)
					{
						SessionManagement.Instance.Send(friend, "GLOBAL:REFRESH_FIRENDS", null);
					}
				}
				cmdCtrl.State["AccountInfo"] = groupInfo.DetailsJson;
			}
		}
		catch (Exception ex)
		{
			cmdCtrl.State["Action"] = "Alert";
			cmdCtrl.State["Message"] = ex.Message;
		}
	}
}
